var markerLayer;//点标记对象
var label;//文本标记对象
var polylineLayer;//折现标记对象
var map;//地图对象
var driving;//驾车路线规划对象
var mapPOIs;
var li_poi = {};//li元素对应的POI对象
let currentSelectedLi;//当前被选择li元素
let groups = [];//分车后的接站点列表数组


window.onload = function () {
    var tMap_script = document.createElement("script");
    tMap_script.type = "text/javascript";
    tMap_script.src = "https://map.qq.com/api/gljs?v=1.exp&key=3KNBZ-GWVKW-I3GRL-Y4QT3-Z5D3E-6AFON&libraries=service,geometry&callback=start";
    document.body.appendChild(tMap_script);

}

async function init() {
    mapPOIs = await window.totalMapPage_API.getPoiMap();
    console.log(mapPOIs);
    // for (const poi of mapPOI) {
    //     POIs.push(poi.poi)
    // }

    //如果点标记存在...
    if (mapPOIs.length > 0) {
        var latlngBounds = new TMap.LatLngBounds();
        // map.setCenter(positionObj.location)
        for (const mapPoi of mapPOIs) {
            latlngBounds.extend(new TMap.LatLng(mapPoi.poi.location.lat, mapPoi.poi.location.lng))//扩展地图显示边界
            markerLayer.add({
                "id": mapPoi.poi.id,   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
                "styleId": 'myStyle',  //指定样式id
                "position": new TMap.LatLng(mapPoi.poi.location.lat, mapPoi.poi.location.lng),  //点标记坐标位置
                "properties": {//自定义属性
                    "title": mapPoi.poi.title,
                }
            })
            label.add({  //添加label
                "id": mapPoi.poi.id,   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
                "styleId": 'label',  //指定样式id
                "position": new TMap.LatLng(mapPoi.poi.location.lat, mapPoi.poi.location.lng),  //点标记坐标位置
                'content': mapPoi.poi.title + "(" + mapPoi.rowspan + ")",
            })
        }
        map.fitBounds(latlngBounds);
    }

    initUI();
}

function start() {

    var center = new TMap.LatLng(23.056084, 113.140666)
    //定义map变量，调用 TMap.Map() 构造函数创建地图
    map = new TMap.Map(document.getElementById('mapContainer'), {
        center: center,//设置地图中心点坐标
        zoom: 17.2,   //设置地图缩放级别
    });

    //点标记器
    markerLayer = new TMap.MultiMarker({
        map: map,  //指定地图容器
        // 样式定义
        styles: {
            //创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
            myStyle: new TMap.MarkerStyle({
                width: 25,  // 点标记样式宽度（像素）
                height: 35, // 点标记样式高度（像素）
                // "src": '../img/marker.png',  //图片路径
                //焦点在图片中的像素位置，一般大头针类似形式的图片以针尖位置做为焦点，圆形点以圆心位置为焦点
                anchor: { x: 16, y: 32 }
            }),
        }
    })


    //初始化label
    label = new TMap.MultiLabel({
        map: map, //设置折线图层显示到哪个地图实例中
        //文字标记样式
        styles: {
            'label': new TMap.LabelStyle({
                'color': '#F20779', //颜色属性
                'size': 20, //文字大小属性
                'offset': { x: 0, y: 15 }, //文字偏移属性单位为像素
                'angle': 0, //文字旋转属性
                'alignment': 'center', //文字水平对齐属性
                'verticalAlignment': 'middle' //文字垂直对齐属性
            })
        },
    });

    //初始化驾车规划路线对象
    driving = new TMap.service.Driving({
        // 新建一个驾车路线规划类
        mp: false, // 是否返回多方案
        policy: 'PICKUP,NAV_POINT_FIRST', // 规划策略
        noStep: false, // 是否需要路线指导
    });

    polylineLayer = new TMap.MultiPolyline({
        map: map,
        styles: {
            style_blue: new TMap.PolylineStyle({
                color: '#3777FF',
                width: 8,
                borderWidth: 5,
                borderColor: '#FFF',
                lineCap: 'round',
            }),
            style_takeCar: new TMap.PolylineStyle({
                color: '#e36176',
                width: 6,
                borderWidth: 1,
                borderColor: '#FFF',
                lineCap: 'round',
            }),
        }
    });

    init();
}

function initUI() {
    console.log("填充接站点列表数据");
    //填充接站点列表数据
    document.getElementById("selectPalceList").innerHTML = "";
    for (const mapPoi of mapPOIs) {
        let newLi = document.createElement("li");
        let newInput = document.createElement("input");
        newInput.type = "checkbox";
        newLi.innerText = mapPoi.poi.title + "(" + mapPoi.rowspan + ")";
        newLi.append(newInput);
        newLi.setAttribute('data-id', mapPoi.poi.id);
        li_poi[mapPoi.poi.id] = mapPoi;

        document.getElementById("selectPalceList").append(newLi);
    }

    // 接站点列表点击事件
    document.getElementById("selectPalceList").querySelectorAll("li").forEach(function (listItem) {
        listItem.addEventListener('click', function (event) {
            // 阻止事件冒泡到父元素
            event.stopPropagation();

            // 找到当前li元素内部的checkbox
            var checkbox = this.querySelector('input[type="checkbox"]');
            if (checkbox) {
                // 触发checkbox的点击事件
                checkbox.click();
            }
            //统计已选择的接站点的人数
            let countLable = document.getElementById("selectPlaceCount");
            countLable.setAttribute('data-count', '0');
            document.getElementById("selectPalceList").querySelectorAll("li").forEach(function (li_ele) {
                if (li_ele.querySelector('input[type="checkbox"]').checked) {
                    let countInt = parseInt(countLable.getAttribute('data-count')) + parseInt(li_poi[li_ele.getAttribute('data-id')].rowspan);
                    countLable.setAttribute('data-count', countInt);
                }
            });
            countLable.innerText = "(已选" + countLable.getAttribute('data-count') + "人)";
        });
    });

    //‘选择接站点’按钮触发事件
    let hasSelectedPlaceList = document.getElementById("hasSelectedPlaceList");
    document.getElementById("selectPlace").onclick = function () {
        polylineLayer.setGeometries([]);//清空折线标记
        document.getElementById("selectPlaceCount").innerText = "(已选0人)";
        groups.push([]);
        let selectPlaceList = document.getElementById("selectPalceList").querySelectorAll("li");
        hasSelectedPlaceList.innerHTML = "";//清空当前编辑的li元素
        selectPlaceList.forEach(function (li) {
            // 获取每个li内的checkbox元素
            var checkbox = li.querySelector('input[type="checkbox"]');

            // 如果checkbox被选中
            if (checkbox !== null && checkbox.checked) {
                li.style.display = 'none';//取消接站点的显示
                checkbox.checked = false;//取消checkbox的选中状态

                let newLi = document.createElement("li");
                newLi.innerText = li.innerText;
                newLi.setAttribute('data-id', li.getAttribute('data-id'));
                newLi.classList.add("liBackgroundColor");
                newLi.onclick = function () {
                    checkLiSelected(newLi);
                    hasSelectedPlaceList.querySelectorAll("li").forEach(function (li) {
                        li.style = "";
                    })
                    newLi.style.backgroundColor = "#9a9ec5";
                    currentSelectedLi = newLi;
                }
                groups[groups.length - 1].push(newLi);
                hasSelectedPlaceList.append(newLi);
                // selectedItems.push(itemText);
            }
        });
        let newBtn = document.createElement("button");
        newBtn.innerText = "第" + groups.length + "车";
        newBtn.onclick = function () {
            hasSelectedPlaceList.innerHTML = "";
            polylineLayer.setGeometries([]);//清空折线标记
            //初始化按钮
            document.getElementById("startBtn").innerText = "起点";
            document.getElementById("endBtn").innerText = "终点";
            document.getElementById("takeCarBtn").innerText = "打车";
            markerLayer.setGeometries([]);
            label.setGeometries([]);
            groups[newBtn.innerText.replace("第", "").replace("车", "") - 1].forEach(function (li) {
                hasSelectedPlaceList.append(li);
                if (li.classList.contains("startLi")) {
                    document.getElementById("startBtn").innerText = "已选";
                } else if (li.classList.contains("endLi")) {
                    document.getElementById("endBtn").innerText = "已选";
                }
                addMark(li_poi[li.getAttribute('data-id')]);
            });
            document.getElementById("textWindow").value = '';//清空文本框信息
        }
        document.getElementById("groupContainer").append(newBtn);
        newBtn.click();
        console.log(groups);
    }

    //检查li的选择状态
    function checkLiSelected(li) {
        if (li.classList.contains("startLi")) {
            document.getElementById("startBtn").innerText = "取消起点";
        }
        if (li.classList.contains("endLi")) {
            document.getElementById("endBtn").innerText = "取消终点";
        }
        if (li.classList.contains("takeCarLi")) {
            document.getElementById("takeCarBtn").innerText = "取消打车";
        } else {
            document.getElementById("takeCarBtn").innerText = "打车";
        }
    }

    document.getElementById("startBtn").onclick = function (event) {
        if (currentSelectedLi && event.target.innerText === "起点") {
            currentSelectedLi.style = '';
            currentSelectedLi.classList.add("startLi");
            document.getElementById("startBtn").innerText = "已选";
        }
        if (currentSelectedLi && event.target.innerText === "取消起点") {
            currentSelectedLi.style = '';
            currentSelectedLi.classList.remove("startLi");
            document.getElementById("startBtn").innerText = "起点";
        }
        currentSelectedLi = null;
    }
    document.getElementById("endBtn").onclick = function (event) {
        if (currentSelectedLi && event.target.innerText === "终点") {
            currentSelectedLi.style = '';
            currentSelectedLi.classList.add("endLi");
            document.getElementById("endBtn").innerText = "已选";
        }
        if (currentSelectedLi && event.target.innerText === "取消终点") {
            currentSelectedLi.style = '';
            currentSelectedLi.classList.remove("endLi");
            document.getElementById("endBtn").innerText = "终点";
        }
        currentSelectedLi = null;
    }
    document.getElementById("takeCarBtn").onclick = function (event) {
        if (currentSelectedLi && event.target.innerText === "打车") {
            currentSelectedLi.style = '';
            currentSelectedLi.classList.add("takeCarLi");
        }
        if (currentSelectedLi && event.target.innerText === "取消打车") {
            currentSelectedLi.style = '';
            currentSelectedLi.classList.remove("takeCarLi");
            document.getElementById("takeCarBtn").innerText = "打车";
        }
        currentSelectedLi = null;
    }

    //开始规划线路
    document.getElementById("startPlanBtn").onclick = function (event) {
        //清空折线标记图层
        polylineLayer.setGeometries([]);
        document.getElementById("textWindow").value = "正在规划线路·";
        let textAreaDisplay = setInterval(function () {
            let text = document.getElementById("textWindow").value;
            if (text.length > 15) {
                text = "正在规划线路·";
            } else {
                text += "·";
            }
            document.getElementById("textWindow").value = text;
        }, 500);

        //获取全部poi之间的规划路线
        let plan_startPoiID;//起点的POI_ID
        let plan_endPoiID;//终点的POI_ID
        let planPois = [];
        let planRoutes = [];//存储各POI之间的规划路线
        let waitToPlanPois_ID = [];//等待排站的poi_ID
        let takeCarPois_ID = [];//打车的poi_ID
        let compare2TakeCarPois_ID = [];//与打车的poi进行距离比较的poi的ID
        let planResult_ID = [];//存储规划结果的poi_ID
        // let takeCarResult_ID = [];//存储打车规划结果的poi_ID数组
        hasSelectedPlaceList.querySelectorAll("li").forEach(function (li) {
            if (li.classList.contains("startLi")) {
                plan_startPoiID = li.getAttribute('data-id');
            } else if (li.classList.contains("endLi")) {
                plan_endPoiID = li.getAttribute('data-id');
            } else if (li.classList.contains("takeCarLi")) {
                takeCarPois_ID.push(li.getAttribute('data-id'));
            } else {
                waitToPlanPois_ID.push(li.getAttribute('data-id'));
            }

            planPois.push(li_poi[li.getAttribute('data-id')]);
        })
        compare2TakeCarPois_ID.push(plan_startPoiID);
        compare2TakeCarPois_ID.push(plan_endPoiID);
        compare2TakeCarPois_ID = compare2TakeCarPois_ID.concat(waitToPlanPois_ID);

        //查询规划路线,并用递归限制并发
        searchRoute(0, 1, planPois.length);
        function searchRoute(i, j, length) {
            if (i == length - 1) {
                clearInterval(textAreaDisplay);
                //**********根据起点和终点,规划最短路径************
                console.log(planRoutes);
                planResult_ID.push(plan_startPoiID);
                let planTimes = waitToPlanPois_ID.length;
                let startPoi_ID = plan_startPoiID;
                for (let i = 0; i < planTimes; i++) {
                    //比较两点之间的距离
                    let minDistance = 99999999999999;
                    let nextPoi_ID;
                    for (const poi_id of waitToPlanPois_ID) {
                        for (const planRoute of planRoutes) {
                            if (planRoute.pois.includes(startPoi_ID) && planRoute.pois.includes(poi_id)) {
                                if (planRoute.route.distance < minDistance) {
                                    minDistance = planRoute.route.distance;
                                    nextPoi_ID = poi_id;
                                }
                            }
                        }
                    }
                    waitToPlanPois_ID = waitToPlanPois_ID.filter(function (poi_id) {
                        return poi_id !== nextPoi_ID;
                    })
                    planResult_ID.push(nextPoi_ID);
                    startPoi_ID = nextPoi_ID;
                }
                planResult_ID.push(plan_endPoiID);
                console.log(planResult_ID);
                let result_Text = '';
                let num2ZH = '一二三四五六七八九';
                let startTime = document.getElementById("startTimeInput").value.replace("：", ":");
                result_Text += "第一站：" + startTime + " " + li_poi[planResult_ID[0]].poi.title + '\n';

                for (let a = 0; a < planResult_ID.length - 1; a++) {
                    //添加规划线路的折线标记
                    polylineLayer.add({
                        "id": planResult_ID[a] + planResult_ID[a + 1],   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
                        "styleId": 'style_blue',  //指定样式id
                        "paths": [
                            Array.from(planRoutes).find(function (planRoute) {
                                return planRoute.pois.includes(planResult_ID[a]) && planRoute.pois.includes(planResult_ID[a + 1]);
                            }).route.polyline
                        ]
                    })
                    //自定义时间计算函数
                    function mTimeCalu(_startTime, duration) {
                        let hour_minutes = _startTime.split(":");
                        let planDuration = Math.ceil(duration / 5) * 5;
                        let caluMinutes = parseInt(hour_minutes[1]) + planDuration;
                        let hour = parseInt(hour_minutes[0]) + Math.floor(caluMinutes / 60);
                        let minutes = caluMinutes % 60;
                        startTime = (hour < 10 ? '0' + hour : hour) + ":" + (minutes < 10 ? '0' + minutes : minutes);
                        return startTime;
                    }
                    //拼接'接站点规划结果'字符串
                    result_Text += "第" + num2ZH.charAt(a + 1) + "站：" + mTimeCalu(startTime, Array.from(planRoutes).find(function (planRoute) {
                        return planRoute.pois.includes(planResult_ID[a]) && planRoute.pois.includes(planResult_ID[a + 1]);
                    }).route.duration) + " " + li_poi[planResult_ID[a + 1]].poi.title + '\n';
                }

                //***********打车线路规划*********** */
                if (takeCarPois_ID.length > 0) {
                    result_Text += "\n（部分客 人需打车接驳汇合，客人凭发票向导游报销）\n";
                }
                for (const takeCarPoi of takeCarPois_ID) {
                    let takeCarMinDistance = 999999999999999;
                    let takeCarTargetPoi_ID;
                    for (let t = 0; t < compare2TakeCarPois_ID.length; t++) {
                        let poisDistance = TMap.geometry.computeDistance([
                            new TMap.LatLng(li_poi[takeCarPoi].poi.location.lat, li_poi[takeCarPoi].poi.location.lng),
                            new TMap.LatLng(li_poi[compare2TakeCarPois_ID[t]].poi.location.lat, li_poi[compare2TakeCarPois_ID[t]].poi.location.lng)
                        ])
                        if (poisDistance < takeCarMinDistance) {
                            takeCarMinDistance = poisDistance;
                            takeCarTargetPoi_ID = compare2TakeCarPois_ID[t];
                        }
                    }
                    //添加打车线路的折线标记
                    polylineLayer.add({
                        "id": takeCarPoi + takeCarTargetPoi_ID,   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
                        "styleId": 'style_takeCar',  //指定样式id
                        "paths": [
                            new TMap.LatLng(li_poi[takeCarPoi].poi.location.lat, li_poi[takeCarPoi].poi.location.lng),
                            new TMap.LatLng(li_poi[takeCarTargetPoi_ID].poi.location.lat, li_poi[takeCarTargetPoi_ID].poi.location.lng)
                        ]
                    })

                    result_Text += li_poi[takeCarPoi].poi.title + "  打车前往  " + li_poi[takeCarTargetPoi_ID].poi.title + '\n';
                }


                //将规划结果展示在文本框中
                document.getElementById("textWindow").value = result_Text;

                return;
            }
            driving.search({
                from: new TMap.LatLng(planPois[i].poi.location.lat, planPois[i].poi.location.lng),
                to: new TMap.LatLng(planPois[j].poi.location.lat, planPois[j].poi.location.lng),
            })
                .then((result) => {
                    planRoutes.push({
                        pois: [planPois[i].poi.id, planPois[j].poi.id],
                        route: result.result.routes[0]
                    });
                    j++;
                    if (j == length) {
                        i++;
                        j = i + 1;
                    }
                    setTimeout(() => {
                        searchRoute(i, j, length);
                    }, 200);
                })
        }
    }
}

function addMark(mapPoi) {
    //更新地图
    markerLayer.add({
        "id": mapPoi.poi.id,   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
        "styleId": 'myStyle',  //指定样式id
        "position": new TMap.LatLng(mapPoi.poi.location.lat, mapPoi.poi.location.lng),  //点标记坐标位置
        "properties": {//自定义属性
            "title": mapPoi.poi.title,
        }
    })
    label.add({  //添加label
        "id": mapPoi.poi.id,   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
        "styleId": 'label',  //指定样式id
        "position": new TMap.LatLng(mapPoi.poi.location.lat, mapPoi.poi.location.lng),  //点标记坐标位置
        'content': mapPoi.poi.title + "(" + mapPoi.rowspan + ")",
    })
}

